<template>
  <div class="dashboard-container">
    <el-card class="dashboard-card">
      <div class="header-container">
        <h2 class="dashboard-title">数据统计概览</h2>
        <el-button type="primary" @click="exportReport">导出报表</el-button>
      </div>
      <div class="charts-wrapper">
        <div class="chart-block chart-block--main">
          <h3 class="chart-title">租赁数量（本月每日）</h3>
          <div ref="rentalLineRef" class="echarts" style="width: 100%; height: 320px;"></div>
        </div>
        <div class="chart-block chart-block--side">
          <h3 class="chart-title">客户租赁次数前5名</h3>
          <div ref="customerBarRef" class="echarts" style="width: 100%; height: 320px;"></div>
        </div>
        <div class="chart-block chart-block--side">
          <h3 class="chart-title">维修数量（本月每日）</h3>
          <div ref="repairBarRef" class="echarts" style="width: 100%; height: 320px;"></div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'

const rentalLineRef = ref(null)
const customerBarRef = ref(null)
const repairBarRef = ref(null)

// 数据源
const rentalList = ref([])
const repairList = ref([])
const customerList = ref([])

// 获取租赁数据
const fetchRentalList = async () => {
  const token = localStorage.getItem('Token')
  const response = await fetch('http://localhost:8080/rental/list?page=1&size=1000', {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      'Token': token
    }
  })
  if (!response.ok) return []
  const result = await response.json()
  console.log(result)
  if (result.code === 200) {
    return result.data.records || []
  }
  return []
}

// 获取维修数据
const fetchRepairList = async () => {
  const token = localStorage.getItem('Token')
  const response = await fetch('http://localhost:8080/repair/list?page=1&size=1000', {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      'Token': token
    }
  })
  if (!response.ok) return []
  const result = await response.json()
  if (result.code === 200) {
    return result.data.records || []
  }
  return []
}

// 获取客户数据
const fetchCustomerList = async () => {
  const token = localStorage.getItem('Token')
  const response = await fetch('http://localhost:8080/customers/list?page=1&size=1000', {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      'Token': token
    }
  })
  if (!response.ok) return []
  const result = await response.json()
  if (result.code === 200) {
    return result.data.records || []
  }
  return []
}

// 数据处理
function getRentalDailyData(list) {
  // 统计每日租赁数量
  const dayMap = {}
  list.forEach(item => {
    const date = item.startRentalTime || item.startDate
    if (!date) return
    const day = date.slice(0, 10) // yyyy-MM-dd
    dayMap[day] = (dayMap[day] || 0) + 1
  })
  const days = Object.keys(dayMap).sort()
  const counts = days.map(d => dayMap[d])
  return { days, counts }
}

function getCustomerTop5ByRentalTimes(list) {
  // 取rentalTimes前5名
  const arr = list.map(item => ({ name: item.name, count: item.rentalTimes || 0 }))
  arr.sort((a, b) => b.count - a.count)
  const top5 = arr.slice(0, 5)
  return {
    names: top5.map(i => i.name),
    counts: top5.map(i => i.count)
  }
}

function getRepairDailyDataThisMonth(list) {
  // 只统计本月每日维修数量，补全本月所有日期
  const now = new Date()
  const year = now.getFullYear()
  const month = (now.getMonth() + 1).toString().padStart(2, '0')
  const ym = `${year}-${month}`
  // 获取本月天数
  const daysInMonth = new Date(year, now.getMonth() + 1, 0).getDate()
  const allDays = Array.from({ length: daysInMonth }, (_, i) => `${ym}-${(i + 1).toString().padStart(2, '0')}`)
  // 统计数据
  const dayMap = {}
  list.forEach(item => {
    const date = item.repairTime || item.reportDate
    if (!date) return
    if (!date.startsWith(ym)) return
    const day = date.slice(0, 10)
    dayMap[day] = (dayMap[day] || 0) + 1
  })
  // 补全所有天
  const counts = allDays.map(day => dayMap[day] || 0)
  return { days: allDays, counts }
}

function getRentalDailyDataThisMonth(list) {
  // 只统计本月每日租赁数量，补全本月所有日期
  const now = new Date()
  const year = now.getFullYear()
  const month = (now.getMonth() + 1).toString().padStart(2, '0')
  const ym = `${year}-${month}`
  // 获取本月天数
  const daysInMonth = new Date(year, now.getMonth() + 1, 0).getDate()
  const allDays = Array.from({ length: daysInMonth }, (_, i) => `${ym}-${(i + 1).toString().padStart(2, '0')}`)
  // 统计数据
  const dayMap = {}
  list.forEach(item => {
    const date = item.startRentalTime || item.startDate
    if (!date) return
    if (!date.startsWith(ym)) return
    const day = date.slice(0, 10)
    dayMap[day] = (dayMap[day] || 0) + 1
  })
  // 补全所有天
  const counts = allDays.map(day => dayMap[day] || 0)
  return { days: allDays, counts }
}

const exportReport = async () => {
  const token = localStorage.getItem('Token')
  try {
    const response = await fetch('http://localhost:8080/report/export', {
      method: 'GET',
      headers: {
        'Token': token
      },
    })
    if (!response.ok) {
      alert('导出报表失败')
      return
    }
    const blob = await response.blob()
    const disposition = response.headers.get('content-disposition')
    let filename = 'report.xlsx'
    if (disposition) {
      const match = disposition.match(/filename="([^"]+)"/);
      if (match && match[1]) {
        filename = decodeURIComponent(match[1]);
      }
    }
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(link.href)
  } catch (err) {
    console.error(err)
    alert('导出报表时出错')
  }
}

// 渲染图表
function renderCharts() {
  // 租赁折线图（本月每日）
  const rentalData = getRentalDailyDataThisMonth(rentalList.value)
  const rentalChart = echarts.init(rentalLineRef.value)
  rentalChart.setOption({
    title: { text: '租赁数量（本月每日）', left: 'center', top: 10, textStyle: { fontSize: 16 } },
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: rentalData.days },
    yAxis: { type: 'value' },
    series: [{ name: '租赁数量', type: 'line', data: rentalData.counts, smooth: true }]
  })
  // 客户排行榜（用客户表数据，前5名）
  const customerData = getCustomerTop5ByRentalTimes(customerList.value)
  const customerChart = echarts.init(customerBarRef.value)
  customerChart.setOption({
    title: { text: '客户租赁次数前5名', left: 'center', top: 10, textStyle: { fontSize: 16 } },
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: customerData.names,
      axisLabel: {
        interval: 0,
        rotate: 45,
        overflow: 'truncate',
        width: 80,
        formatter: function(value) {
          return value.length > 6 ? value.slice(0, 6) + '...' : value
        }
      }
    },
    yAxis: { type: 'value' },
    series: [{ name: '租赁次数', type: 'bar', data: customerData.counts, itemStyle: { color: '#409EFF' } }]
  })
  // 维修柱状图（本月每日）
  const repairData = getRepairDailyDataThisMonth(repairList.value)
  const repairChart = echarts.init(repairBarRef.value)
  repairChart.setOption({
    title: { text: '维修数量（本月每日）', left: 'center', top: 10, textStyle: { fontSize: 16 } },
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: repairData.days },
    yAxis: { type: 'value' },
    series: [{ name: '维修数量', type: 'bar', data: repairData.counts, itemStyle: { color: '#67C23A' } }]
  })
  // 响应式
  window.addEventListener('resize', () => {
    rentalChart.resize()
    customerChart.resize()
    repairChart.resize()
  })
}

onMounted(async () => {
  rentalList.value = await fetchRentalList()
  repairList.value = await fetchRepairList()
  customerList.value = await fetchCustomerList()
  await nextTick()
  renderCharts()
})
</script>

<style scoped>
.dashboard-container {
  padding: 32px 12px 32px 12px;
  background: linear-gradient(135deg, #f8fafc 0%, #e0e7ef 100%);
  min-height: 100vh;
}
.dashboard-card {
  max-width: 1300px;
  margin: 0 auto;
  box-shadow: 0 8px 32px 0 rgba(60, 80, 120, 0.10), 0 1.5px 4px 0 rgba(60, 80, 120, 0.08);
  border-radius: 18px;
  border: none;
  background: #fff;
  padding-bottom: 32px;
}
.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.dashboard-title {
  font-size: 2.1rem;
  font-weight: 700;
  color: #2d3a4b;
  letter-spacing: 2px;
  margin: 0 0 32px 0;
  text-align: left;
  text-shadow: 0 2px 8px #e0e7ef;
}
.charts-wrapper {
  display: flex;
  flex-wrap: wrap;
  gap: 32px;
  justify-content: space-between;
}
.chart-block {
  flex: 1 1 370px;
  min-width: 320px;
  max-width: 420px;
  background: linear-gradient(135deg, #f6faff 60%, #e3eaf6 100%);
  border-radius: 20px;
  box-shadow: 0 4px 16px 0 rgba(60, 80, 120, 0.08);
  padding: 20px 14px 14px 14px;
  margin-bottom: 24px;
  transition: box-shadow 0.2s, transform 0.2s;
  position: relative;
  overflow: hidden;
}
.chart-block--main {
  flex: 2 1 600px;
  min-width: 420px;
  max-width: 700px;
  background: linear-gradient(135deg, #e0f7fa 60%, #e3eaf6 100%);
}
.chart-block:hover {
  box-shadow: 0 8px 32px 0 rgba(60, 80, 120, 0.16);
  transform: translateY(-4px) scale(1.02);
  z-index: 2;
}
.chart-title {
  font-size: 1.18rem;
  font-weight: 600;
  color: #3a4a5d;
  margin-bottom: 10px;
  letter-spacing: 1px;
  text-align: left;
}
.echarts {
  margin-top: 10px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px 0 rgba(60, 80, 120, 0.06);
}
@media (max-width: 1100px) {
  .charts-wrapper {
    flex-direction: column;
    gap: 24px;
  }
  .chart-block, .chart-block--main {
    max-width: 100%;
    min-width: 0;
    flex: 1 1 100%;
  }
}
</style> 